package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

import com.example.demo.bean.STitle;
import com.example.demo.common.exception.DataValidException;
import com.example.demo.mapper.SEmpMapper;
import com.example.demo.mapper.STitleMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class STitleService {
	@Autowired 
	private STitleMapper stMapper;
	@Autowired
	private SEmpMapper seMapper;
	//搜索显示所有的职位信息
	public PageInfo<STitle> findAllByPage(int pageNum,int pageSize){
		PageHelper.startPage(pageNum,pageSize);
		//执行查找行为
		List<STitle> list=stMapper.selectAll();
		if (list==null) {
			list=new ArrayList<>(0);
		}
		return new PageInfo<STitle>(list);
	}
	
	//按照名字查找职位信息
	public PageInfo<STitle> findByName(String title,int pageNum,int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		if (title==null||"".equals(title)) {
			throw new DataValidException("请输入职位名称");
		}
		List<STitle> list=stMapper.selectByName(title);
		if (list==null) {
			list= new ArrayList<>(0);
		}
		
		return new PageInfo<STitle>(list);
	}
	
	
	//添加职位
	public int saveTitle(STitle st) {
		//判断输入是否为空
		if (st==null||"".equals(st)) {
			throw new DataValidException("请输入完整信息");
		}
		//判断是否存在
		if (st==stMapper.selectByName(st.getTitle())) {
			throw new DataValidException("已经存在该职位");
		}
		stMapper.insert(st);
		return 0;
	}
	
	//删除职位
	//作为emp的外键存在
	public int deleteByTitle(String title) {
		//判断输入的是否为空
		if (title==null||"".equals(title)) {
			throw new DataValidException("请输入完整信息");
		}
		//判断数据库中是否存在该职位
		if (stMapper.selectByName(title)==null) {
			throw new DataValidException("删除失败");
		}
		STitle st=stMapper.selectByTitle(title);
		if (!seMapper.selectByTitle(st.getTitle()).isEmpty()) {
			throw new DataValidException("存在下属信息员工，请删除下属员工后，在进行删除");
		}
		stMapper.deleteByPrimaryKey(title);
		return 0;
	}
	
	//批量删除
	public int batchDelete(String [] title) {
		//判断输入的数据是否为空
		if (title.length==0||title==null) {
			throw new DataValidException("请选择一批");
		}
		//判断其中是否有不存在的数据
		for (String i : title) {
			if (stMapper.selectByName(i)==null) {
				throw new DataValidException("删除失败");
			}
			STitle st=stMapper.selectByTitle(i);
			if (!seMapper.selectByTitle(st.getTitle()).isEmpty()) {
				throw new DataValidException("存在下属信息员工，请删除下属员工后，在进行删除");
			}
		}
		//删除数据
		stMapper.batchDeleteByTitle(title);
		return 0;
		
	}
}
